#!/bin/bash

## eg: sh serve_one.sh start user rpc

base_path="/home/zhubing/web/golang/src/go-zero/book"

act_type=$1     # start stop restart
service_name=$2 # user sstwords search shorturl
service_type=$3 # api | rpc

if [ "${act_type}" == "" ]; then
    echo "缺少参数1"
    exit 1
fi

if [ "${service_name}" == "" ]; then
    echo "缺少参数2"
    exit 1
fi

if [ "${service_type}" == "" ]; then
    echo "缺少参数3"
    exit 1
fi

now_path="${base_path}/service/${service_name}/cmd/${service_type}"
log_path="${now_path}/logs/${service_name}.log"
pid_path="${now_path}/bin/pid"

if [ ${act_type} == "start" ]; then
    nohup go run "${now_path}/${service_name}.go" -f "${now_path}/etc/${service_name}.yaml" >>${log_path} 2>&1 &
    echo "$!" >${pid_path}
elif [ ${act_type} == "stop" ]; then
    pkill -P $(cat ${pid_path}) # 通过ppid stop
elif [${act_type} == "restart"]; then

    pkill -TERM -P $(cat ${pid_path}) # 通过ppid stop

    nohup go run "${now_path}/${service_name}.go" -f "${now_path}/etc/${service_name}.yaml" >>${log_path} 2>&1 &
    echo "$!" >${pid_path}
else
    echo "Please make sure the position variable is start or stop."
fi
